<?php

/**
 *   OPENSHOP 管理中心公用函数库
 * 
 *   @link        http://baison.com.cn
 *   @copyright   Baison, Inc.
 *   @package     OpenShop
 *   @version     $Id: lib_main.php,v 1.0 2009/06/12 07:35:58 modified $
 *   @author      FillBag <fillbag@hotmail.com>
 */

if (!defined('IN_OS')){
    die('Access Denied');
}
function UPCAbarcode($code) 
{ 
    $lw = 2; $hi = 100; 
    $Lencode = array('0001101','0011001','0010011','0111101','0100011', 
                    '0110001','0101111','0111011','0110111','0001011'); 
    $Rencode = array('1110010','1100110','1101100','1000010','1011100', 
                    '1001110','1010000','1000100','1001000','1110100'); 
    $ends = '101'; $center = '01010'; 
	    
    /* UPC-A Must be 11 digits, we compute the checksum. */ 
    if ( strlen($code) != 11 ) { die("UPC-A Must be 11 digits."); } 
 
    /* Compute the EAN-13 Checksum digit */ 
    $ncode = '0'.$code; 
    $even = 0; $odd = 0; 
    for ($x=0;$x<12;$x++) 
    { 
        if ($x % 2) { $odd += $ncode[$x]; } else { $even += $ncode[$x]; } 
    } 
 
    $code.=(10 - (($odd * 3 + $even) % 10)) % 10; 
 
    /* Create the bar encoding using a binary string */ 
    $bars=$ends; 
    $bars.=$Lencode[$code[0]]; 
    for($x=1;$x<6;$x++) 
    { 
        $bars.=$Lencode[$code[$x]]; 
    } 
 
    $bars.=$center; 
 
    for($x=6;$x<12;$x++) 
    { 
        $bars.=$Rencode[$code[$x]]; 
    } 
 
    $bars.=$ends; 
 
    /* Generate the Barcode Image */ 
    $img = ImageCreate($lw*95+30,$hi+30); 
    $fg = ImageColorAllocate($img, 0, 0, 0); 
    $bg = ImageColorAllocate($img, 255, 255, 255); 
    ImageFilledRectangle($img, 0, 0, $lw*95+30, $hi+30, $bg); 
 
    $shift=10; 
 
    for ($x=0;$x<strlen($bars);$x++) 
    { 
        if (($x<10) || ($x>=45 && $x<50) || ($x >=85)) { $sh=10; } else { $sh=0; } 
        if ($bars[$x] == '1') { $color = $fg; } else { $color = $bg; } 
        ImageFilledRectangle($img, ($x*$lw)+15,5,($x+1)*$lw+14,$hi+5+$sh,$color); 
    } 
 
    /* Add the Human Readable Label */ 
    ImageString($img,4,5,$hi-5,$code[0],$fg); 
 
    for ($x=0;$x<5;$x++) 
    { 
        ImageString($img,5,$lw*(13+$x*6)+15,$hi+5,$code[$x+1],$fg); 
        ImageString($img,5,$lw*(53+$x*6)+15,$hi+5,$code[$x+6],$fg); 
    } 
 
    ImageString($img,4,$lw*95+17,$hi-5,$code[11],$fg); 
 
    /* Output the Header and Content. */ 
    header("Content-Type: image/png"); 
    ImagePNG($img); 
 
} 

function EAN_13($code) {
  $lw = 2;
  $hi = 100;
  // the guide code is no coding,is used to show the left part coding type//
  // Array guide is used to record the EAN_13 is left part coding type//
  $Guide = array(1=> 'AAAAAA','AABABB','AABBAB','ABAABB','ABBAAB','ABBBAA','ABABAB','ABABBA','ABBABA');
  $Lstart ='101';
  $Lencode = array("A" =>  array('0001101','0011001','0010011','0111101','0100011','0110001','0101111','0111011','0110111','0001011'),
                   "B" =>  array('0100111','0110011','0011011','0100001','0011101','0111001','0000101','0010001','0001001','0010111'));
  $Rencode = array('1110010','1100110','1101100','1000010','1011100',
                   '1001110','1010000','1000100','1001000','1110100');                  
                                  
  $center = '01010';
  
  $ends = '101';
  if ( strlen($code) != 13 )
   { die("UPC-A Must be 13 digits."); }
$lsum =0;
$rsum =0;
  for($i=0;$i<(strlen($code)-1);$i++)
  {
    if($i % 2)
        {
         // $odd += $ncode[$x]
          $lsum +=(int)$code[$i];
         }else{
          $rsum +=(int)$code[$i];
         }
          
  }       
  $tsum = $lsum*3 + $rsum;
    if($code[12] != (10-($tsum % 10)))
        {
           die("the code is bad!");
    }
       
// echo $Guide[$code[0]];
  $barcode = $Lstart;
  for($i=1;$i<=6;$i++)
  {
    $barcode .= $Lencode [$Guide[$code[0]][($i-1)]] [$code[$i]];
  }
  $barcode .= $center;
  
  for($i=7;$i<13;$i++)
  {
    $barcode .= $Rencode[$code[($i)]] ;
  }
  $barcode .= $ends;
  
    $img = ImageCreate($lw*95+60,$hi+30);
  $fg = ImageColorAllocate($img, 0, 0, 0);
  $bg = ImageColorAllocate($img, 255, 255, 255);
  ImageFilledRectangle($img, 0, 0, $lw*95+60, $hi+30, $bg);
  $shift=10;
  for ($x=0;$x<strlen($barcode);$x++) {
    if (($x<4) || ($x>=45 && $x<50) || ($x >=92))
          {
            $sh=10;
          } else {
            $sh=0;
          }
    if ($barcode[$x] == '1')
        {
          $color = $fg;
    } else {
          $color = $bg;
        }
    ImageFilledRectangle($img, ($x*$lw)+30,5,($x+1)*$lw+29,$hi+5+$sh,$color);
  }
  /* Add the Human Readable Label */
  ImageString($img,5,20,$hi+5,$code[0],$fg);
  for ($x=0;$x<6;$x++) {
    ImageString($img,5,$lw*(8+$x*6)+30,$hi+5,$code[$x+1],$fg);
    ImageString($img,5,$lw*(53+$x*6)+30,$hi+5,$code[$x+7],$fg);
  }
// ImageString($img,4,$lw*95+17,$hi-5,$code[12],$fg);
  /* Output the Header and Content. */
  header("Content-Type: image/png");
  ImagePNG($img);
   
}
/**
 * 获得所有模块的名称以及链接地址
 *
 * @access      public
 * @param       string      $directory      插件存放的目录
 * @return      array
 */
function read_modules($directory = '.')
{
    $dir         = @opendir($directory);
    $set_modules = true;
    $modules     = array();

    while (false !== ($file = @readdir($dir)))
    {
        if (preg_match("/^.*?\.php$/", $file))
        {
            include_once($directory. '/' .$file);
        }
    }

    @closedir($dir);
    unset($set_modules);
    foreach ($modules AS $key => $value)
    {
        ksort($modules[$key]);
    }
    ksort($modules);

    return $modules;
}

function repeat_act(){
	$lasthash = $_COOKIE["lasthash"]; //读取上一次设置的Cookie值
	if(count($_REQUEST)) { 
	    $long = ""; 
	    while(list($key,$value)=each($_REQUEST)){
	    	if($key != 'lasthash')
	        $long.=$value; 	    	
	    }
	    $hash = md5($long); 
	    setcookie("lasthash",$hash,time()+60*60*24*30); //重新设置cookie
	}
	if($lasthash!=$hash) { 
	    // 如果两次的MD5值不一样就对数据进行进一步操作 
	    return FALSE;
	}else{
	    return TRUE;		
	}
}

/**
 * 系统提示信息
 *
 * @access      public
 * @param       string      msg_detail      消息内容
 * @param       int         msg_type        消息类型， 0消息，1错误，2询问
 * @param       array       links           可选的链接
 * @param       boolen      $auto_redirect  是否需要自动跳转
 * @return      void
 */
function sys_msg($msg_detail, $msg_type = 0, $links = array(), $auto_redirect = true)
{	
    if (count($links) == 0)
    {
        $links[0]['text'] = '返回上一页';
        $links[0]['href'] = 'javascript:history.go(-1)';
    }
    
    if(isset($links[0]['flag']) && $links[0]['flag'] == 'login_failed'){
    	$GLOBALS['smarty']->assign('flag',  $links[0]['flag']);
    }
    
    assign_query_info();
    
    $GLOBALS['smarty']->assign('ur_here',     '系统信息');
    $GLOBALS['smarty']->assign('msg_detail',  $msg_detail);
    $GLOBALS['smarty']->assign('msg_type',    $msg_type);
    $GLOBALS['smarty']->assign('links',       $links);
    $GLOBALS['smarty']->assign('default_url', $links[0]['href']);
    $GLOBALS['smarty']->assign('auto_redirect', $auto_redirect);
    $GLOBALS['smarty']->display('message.tpl');
    exit;
}

/**
 * 记录管理员的操作内容
 *
 * @access  public
 * @param   string      $sn         数据的唯一值
 * @param   string      $action     操作的类型
 * @param   string      $content    操作的内容
 * @return  void
 */
function admin_log($sn = '', $action, $content)
{
	 $log_info = $GLOBALS['_LANG']['log_action'][$action] . $GLOBALS['_LANG']['log_action'][$content] .': '. addslashes($sn);
     if($content=='top_api'){
     	  $sql = 'INSERT INTO ' . $GLOBALS['os']->table('admin_log') . ' (log_time, user_id, log_info, ip_address,type) ' .
            " VALUES ('" . gmtime() . "', $_SESSION[admin_id], '" . addslashes($log_info) . "', '" . real_ip() . "', 'TOP')";
     }  else {
     	  $sql = 'INSERT INTO ' . $GLOBALS['os']->table('admin_log') . ' (log_time, user_id, log_info, ip_address) ' .
            " VALUES ('" . gmtime() . "', $_SESSION[admin_id], '" . stripslashes($log_info) . "', '" . real_ip() . "')";
     }     
    $GLOBALS['db']->query($sql); 
}

function order_print_log($sn = '', $type,$info = '')
{
	
	if($type == 1)
	{
		$info = '订单';
	}elseif ($type == 2)
	{
		$info = '配送单';
	}
	
    $log_info = '打印'.$info.': '. addslashes($sn);

    $sql = 'INSERT INTO ' . $GLOBALS['os']->table('order_printlog') . ' (log_time, user_id, log_info, ip_address, print_type) ' .
            " VALUES ('" . gmtime() . "', $_SESSION[admin_id], '" . stripslashes($log_info) . "', '" . real_ip() . "',".$type.")";
    $GLOBALS['db']->query($sql);
}

/**
 * 将通过表单提交过来的年月日变量合成为"2004-05-10"的格式。
 *
 * 此函数适用于通过smarty函数html_select_date生成的下拉日期。
 *
 * @param  string $prefix      年月日变量的共同的前缀。
 * @return date                日期变量。
 */
function sys_joindate($prefix)
{
    /* 返回年-月-日的日期格式 */
    $year  = empty($_POST[$prefix . 'Year']) ? '0' :  $_POST[$prefix . 'Year'];
    $month = empty($_POST[$prefix . 'Month']) ? '0' : $_POST[$prefix . 'Month'];
    $day   = empty($_POST[$prefix . 'Day']) ? '0' : $_POST[$prefix . 'Day'];

    return $year . '-' . $month . '-' . $day;
}

/**
 * 设置管理员的session内容
 *
 * @access  public
 * @param   integer $user_id        管理员编号
 * @param   string  $username       管理员姓名
 * @param   string  $action_list    权限列表
 * @param   string  $last_time      最后登录时间
 * @return  void
 */
function set_admin_session($user_id, $username, $action_list, $role_list, $last_time)
{
    $_SESSION['admin_id']    = $user_id;
    $_SESSION['admin_name']  = $username;
    $_SESSION['action_list'] = $action_list;
    $_SESSION['role_list']   = $role_list;
    $_SESSION['last_check']  = $last_time; // 用于保存最后一次检查订单的时间
}

/**
 * 插入一个配置信息
 *
 * @access  public
 * @param   string      $parent     分组的code
 * @param   string      $code       该配置信息的唯一标识
 * @param   string      $value      该配置信息值
 * @return  void
 */
function insert_config($parent, $code, $value)
{
    global $os, $db, $_LANG;

    $sql = 'SELECT id FROM ' . $os->table('shop_config') . " WHERE code = '$parent' AND type = 1";
    $parent_id = $db->getOne($sql);

    $sql = 'INSERT INTO ' . $os->table('shop_config') . ' (parent_id, code, value) ' .
            "VALUES('$parent_id', '$code', '$value')";
    $db->query($sql);
}

/**
 * 判断管理员对某一个操作是否有权限。
 *
 * 根据当前对应的action_code，然后再和用户session里面的action_list做匹配，以此来决定是否可以继续执行。
 * @param     string    $priv_str    操作对应的priv_str
 * @param     string    $msg_type       返回的类型
 * @return true/false
 */

function admin_priv($priv_str='', $msg_type = '' , $msg_output = true)
{

    if ($_SESSION['action_list'] == 'all')
    {
        return true;
    }
    
    if(empty($priv_str)){
    	$priv_str = basename($_SERVER['REQUEST_URI']);
    	$priv_str = strrpos($priv_str, '&')? substr($priv_str, 0, strrpos($priv_str, '&')) : $priv_str;
    	$sql = "SELECT action_id,parent_id FROM " . $GLOBALS['os']->table('acl_action') . " WHERE type='url' AND action_code='$priv_str'";
    }else{
    	$sql = "SELECT action_id,parent_id FROM " . $GLOBALS['os']->table('acl_action') . " WHERE type='act' AND action_code='$priv_str'";    	
    }
    
    $priv_row = $GLOBALS['db']->getRow($sql);
    $privilege_arr = explode(',', $_SESSION['action_list']);
    if (in_array($priv_row['parent_id'], $privilege_arr)===true && in_array($priv_row['action_id'], $privilege_arr)===true)
    {
        return true;
    }
    else
    {
        $link[] = array('text' => '返回上一页', 'href' => 'javascript:history.back(-1)');
        if ( $msg_output)
        {
            sys_msg('对不起,您没有执行此项操作的权限!', 0, $link);
        }
        return false;
    }
}

/**
 * 检查管理员权限
 *
 * @access  public
 * @param   string  $authz
 * @return  boolean
 */
function check_authz($authz)
{
    if ($_SESSION['action_list'] == 'all')
    {
        return true;
    }
    $priv_row = $GLOBALS['db']->getRow("SELECT action_id,parent_id FROM " . $GLOBALS['os']->table('acl_action') . " WHERE type='act' AND action_code='$authz'");
    $privilege_arr = explode(',', $_SESSION['action_list']);
    if (in_array($priv_row['parent_id'], $privilege_arr)===true && in_array($priv_row['action_id'], $privilege_arr)===true)
    {
        return true;
    }else{
		return false;   	
    }
}

/**
 * 检查管理员权限，返回JSON格式数剧
 *
 * @access  public
 * @param   string  $authz
 * @return  void
 */
function check_authz_json($authz)
{
    if (!check_authz($authz))
    {
        make_json_error('对不起,您没有执行此项操作的权限!');
    }
}

/**
 * 取得红包类型数组（用于生成下拉列表）
 *
 * @return  array       分类数组 bonus_typeid => bonus_type_name
 */
function get_bonus_type()
{
    $bonus = array();
    $sql = 'SELECT type_id, type_name, type_money FROM ' . $GLOBALS['os']->table('bonus_type') .
           ' WHERE send_type = 3';
    $res = $GLOBALS['db']->query($sql);

    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        $bonus[$row['type_id']] = $row['type_name'].' [' .sprintf($GLOBALS['_CFG']['currency_format'], $row['type_money']).']';
    }

    return $bonus;
}

/**
 * 取得用户等级数组,按用户级别排序
 * @param   bool      $is_special      是否只显示特殊客户组
 * @return  array     rank_id=>rank_name
 */
function get_rank_list($is_special = false)
{
    $rank_list = array();
    $sql = 'SELECT rank_id, rank_name, min_points FROM ' . $GLOBALS['os']->table('user_rank');
    if ($is_special)
    {
        $sql .= ' WHERE special_rank = 1';
    }
    $sql .= ' ORDER BY min_points';

    $res = $GLOBALS['db']->query($sql);

    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        $rank_list[$row['rank_id']] = $row['rank_name'];
    }

    return $rank_list;
}

/**
 * 按等级取得用户列表（用于生成下拉列表）
 *
 * @return  array       分类数组 user_id => user_name
 */
function get_user_rank($rankid, $where)
{
    $user_list = array();
    $sql = 'SELECT user_id, user_name FROM ' . $GLOBALS['os']->table('users') . $where.
           ' ORDER BY user_id DESC';
    $res = $GLOBALS['db']->query($sql);

    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        $user_list[$row['user_id']] = $row['user_name'];
    }

    return $user_list;
}

/**
 * 取得广告位置数组（用于生成下拉列表）
 *
 * @return  array       分类数组 position_id => position_name
 */
function get_position_list()
{
    $position_list = array();
    $sql = 'SELECT position_id, position_name, ad_width, ad_height '.
           'FROM ' . $GLOBALS['os']->table('ad_position');
    $res = $GLOBALS['db']->query($sql);

    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        $position_list[$row['position_id']] = $row['position_name']. ' [' .$row['ad_width']. 'x' .$row['ad_height']. ']';
    }

    return $position_list;
}

/**
 * 生成编辑器
 * @param   string  input_name  输入框名称
 * @param   string  input_value 输入框值
 */
function create_html_editor($input_name, $input_value = '')
{
    global $smarty;

    $editor = new FCKeditor($input_name);
    $editor->BasePath   = '../includes/fckeditor/';
    $editor->ToolbarSet = 'Normal';
    $editor->Width      = '100%';
    $editor->Height     = '320';
    $editor->Value      = $input_value;
    $FCKeditor = $editor->CreateHtml();
    $smarty->assign('FCKeditor', $FCKeditor);
}

/**
 * 取得商品列表：用于把商品添加到组合、关联类、赠品类
 * @param   object  $filters    过滤条件
 */
function get_goods_list($filter)
{
    $filter->keyword = json_str_iconv($filter->keyword);
    $where = get_where_sql($filter); // 取得过滤条件

    /* 取得数据 */
    $sql = 'SELECT goods_id, goods_name, goods_sn, shop_price '.
           'FROM ' . $GLOBALS['os']->table('goods') . ' AS g ' . $where;
    $row = $GLOBALS['db']->getAll($sql);

    return $row;
}

/**
 * 取得文章列表：用于商品关联文章
 * @param   object  $filters    过滤条件
 */
function get_article_list($filter)
{
    /* 创建数据容器对象 */
    $ol = new OptionList();

    /* 取得过滤条件 */
    $where = ' WHERE a.cat_id = c.cat_id AND c.cat_type = 1 ';
    $where .= isset($filter->title) ? " AND a.title LIKE '%" . mysql_like_quote($filter->title) . "%'" : '';

    /* 取得数据 */
    $sql = 'SELECT a.article_id, a.title '.
           'FROM ' .$GLOBALS['os']->table('article'). ' AS a, ' .$GLOBALS['os']->table('article_cat'). ' AS c ' . $where;
    $res = $GLOBALS['db']->query($sql);

    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        $ol->add_option($row['article_id'], $row['title']);
    }

    /* 生成列表 */
    $ol->build_select();
}

/**
 * 返回是否
 * @param   int     $var    变量 1, 0
 */
function get_yes_no($var)
{
    return empty($var) ? '<img src="images/no.gif" border="0" />' : '<img src="images/yes.gif" border="0" />';
}

/**
 * 生成过滤条件：用于 get_goodslist 和 get_goods_list
 * @param   object  $filter
 * @return  string
 */
function get_where_sql($filter)
{
    $time = date('Y-m-d');

    $where  = isset($filter->is_delete) && $filter->is_delete == '1' ?
        ' WHERE is_delete = 1 ' : ' WHERE is_delete = 0 ';
    $where .= (isset($filter->real_goods) && ($filter->real_goods > -1)) ? ' AND is_real = ' . intval($filter->real_goods) : '';
    $where .= isset($filter->cat_id) && $filter->cat_id > 0 ? ' AND ' . get_children($filter->cat_id) : '';
    $where .= isset($filter->brand_id) && $filter->brand_id > 0 ? " AND brand_id = '" . $filter->brand_id . "'" : '';
    $where .= isset($filter->intro_type) && $filter->intro_type != '0' ? ' AND ' . $filter->intro_type . " = '1'" : '';
    $where .= isset($filter->intro_type) && $filter->intro_type == 'is_promote' ?
        " AND promote_start_date <= '$time' AND promote_end_date >= '$time' " : '';
    $where .= isset($filter->keyword) && trim($filter->keyword) != '' ?
        " AND (goods_name LIKE '%" . mysql_like_quote($filter->keyword) . "%' OR goods_sn LIKE '%" . mysql_like_quote($filter->keyword) . "%' OR goods_id LIKE '%" . mysql_like_quote($filter->keyword) . "%') " : '';

    $where .= isset($filter->in_ids) ? ' AND goods_id ' . db_create_in($filter->in_ids) : '';
    $where .= isset($filter->exclude) ? ' AND goods_id NOT ' . db_create_in($filter->exclude) : '';
    $where .= isset($filter->stock_warning) ? ' AND goods_number <= warn_number' : '';

    return $where;
}

/**
 * 获取地区列表的函数。
 *
 * @access  public
 * @param   int     $region_id  上级地区id
 * @return  void
 */
function area_list($region_id)
{
    $area_arr = array();

    $sql = 'SELECT * FROM ' . $GLOBALS['os']->table('region').
           " WHERE parent_id = '$region_id' ORDER BY region_id";
    $res = $GLOBALS['db']->query($sql);
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        $row['type']  = ($row['region_type'] == 0) ? $GLOBALS['_LANG']['country']  : '';
        $row['type'] .= ($row['region_type'] == 1) ? $GLOBALS['_LANG']['province'] : '';
        $row['type'] .= ($row['region_type'] == 2) ? $GLOBALS['_LANG']['city']     : '';
        $row['type'] .= ($row['region_type'] == 3) ? $GLOBALS['_LANG']['cantonal'] : '';

        $area_arr[] = $row;
    }

    return $area_arr;
}

/**
 * 取得图表颜色
 *
 * @access  public
 * @param   integer $n  颜色顺序
 * @return  void
 */
function chart_color($n)
{
    /* 随机显示颜色代码 */
    $arr = array('33FF66', 'FF6600', '3399FF', '009966', 'CC3399', 'FFCC33', '6699CC', 'CC3366', '33FF66', 'FF6600', '3399FF');

    if ($n > 8)
    {
        $n = $n % 8;
    }

    return $arr[$n];
}

/**
 * 获得商品类型的列表
 *
 * @access  public
 * @param   integer     $selected   选定的类型编号
 * @return  string
 */
function goods_type_list($selected)
{
    $sql = 'SELECT cat_id, cat_name FROM ' . $GLOBALS['os']->table('goods_type') . ' WHERE enabled = 1';
    $res = $GLOBALS['db']->query($sql);

    $lst = '';
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        $lst .= "<option value='$row[cat_id]'";
        $lst .= ($selected == $row['cat_id']) ? ' selected="true"' : '';
        $lst .= '>' . htmlspecialchars($row['cat_name']). '</option>';
    }

    return $lst;
}

/**
 * 取得货到付款和非货到付款的支付方式
 * @return  array('is_cod' => '', 'is_not_cod' => '')
 */
function get_pay_ids()
{
    $ids = array('is_cod' => '0', 'is_not_cod' => '0');
    $sql = 'SELECT pay_id, is_cod FROM ' .$GLOBALS['os']->table('payment'). ' WHERE enabled = 1';
    $res = $GLOBALS['db']->query($sql);

    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        if ($row['is_cod'])
        {
            $ids['is_cod'] .= ',' . $row['pay_id'];
        }
        else
        {
            $ids['is_not_cod'] .= ',' . $row['pay_id'];
        }
    }

    return $ids;
}

/**
 * 清空表数据
 * @param   string  $table_name 表名称
 */
function truncate_table($table_name)
{
    $sql = 'TRUNCATE TABLE ' .$GLOBALS['os']->table($table_name);

    return $GLOBALS['db']->query($sql);
}

/**
 *  返回字符集列表数组
 *
 * @access  public
 * @param
 *
 * @return void
 */
function get_charset_list()
{
    return array(
        'UTF8'   => 'UTF-8',
        'GB2312' => 'GB2312/GBK',
        'BIG5'   => 'BIG5',
    );
}


/**
 * 创建一个JSON格式的数据
 *
 * @access  public
 * @param   string      $content
 * @param   integer     $error
 * @param   string      $message
 * @param   array       $append
 * @return  void
 */
function make_json_response($content='', $error="0", $message='', $append=array())
{
    include_once(ROOT_PATH . 'includes/cls_json.php');

    $json = new JSON;

    $res = array('error' => $error, 'message' => $message, 'content' => $content);

    if (!empty($append))
    {
        foreach ($append AS $key => $val)
        {
            $res[$key] = $val;
        }
    }

    $val = $json->encode($res);

    exit($val);
}

function make_json_response2($content='', $error="0", $message='', $append=array())
{
    include_once(ROOT_PATH . 'includes/cls_json.php');
    //make_json_error($content);

    $json = new JSON;

    $res = array('error' => $error, 'message' => $message, 'content' => $content);

    if (!empty($append))
    {
        foreach ($append AS $key => $val)
        {
            $res[$key] = $val;
        }
    }

    echo $val = $json->encode($res);

}
/**
 *
 *
 * @access  public
 * @param
 * @return  void
 */
function make_json_result($content, $message='', $append=array())
{
    make_json_response($content, 0, $message, $append);
}

/**
 * 创建一个JSON格式的错误信息
 *
 * @access  public
 * @param   string  $msg
 * @return  void
 */
function make_json_error($msg)
{
    make_json_response('', 1, $msg);
}

/**
 * 根据过滤条件获得排序的标记
 *
 * @access  public
 * @param   array   $filter
 * @return  array
 */
function sort_flag($filter)
{
    $flag['tag']    = 'sort_' . preg_replace('/^.*\./', '', $filter['sort_by']);
    $flag['img']    = '<img src="images/' . ($filter['sort_order'] == "DESC" ? 'sort_desc.gif' : 'sort_asc.gif') . '"/>';

    return $flag;
}

/**
 * 分页的信息加入条件的数组
 *
 * @access  public
 * @return  array
 */
function page_and_size($filter)
{
    if (isset($_REQUEST['page_size']) && intval($_REQUEST['page_size']) > 0)
    {
        $filter['page_size'] = intval($_REQUEST['page_size']);
    }
    elseif (isset($_COOKIE['OSCP']['page_size']) && intval($_COOKIE['OSCP']['page_size']) > 0)
    {
        $filter['page_size'] = intval($_COOKIE['OSCP']['page_size']);
    }
    else
    {
    	if ($filter['from_module'] == 'inventory') {
    		$filter['page_size'] = 10;
    	}else{
    		$filter['page_size'] = 20;
    	}
    	$filter['from_module'] = '';
    }

    /* 每页显示 */
    $filter['page'] = (empty($_REQUEST['page']) || intval($_REQUEST['page']) <= 0) ? 1 : intval($_REQUEST['page']);

    /* page 总数 */
    $filter['page_count'] = (!empty($filter['record_count']) && $filter['record_count'] > 0) ? ceil($filter['record_count'] / $filter['page_size']) : 1;

    /* 边界处理 */
    if ($filter['page'] > $filter['page_count'])
    {
        $filter['page'] = $filter['page_count'];
    }

    $filter['start'] = ($filter['page'] - 1) * $filter['page_size'];

    return $filter;
}

/**
 *  将含有单位的数字转成字节
 *
 * @access  public
 * @param   string      $val        带单位的数字
 *
 * @return  int         $val
 */
function return_bytes($val)
{
    $val = trim($val);
    $last = strtolower($val{strlen($val)-1});
    switch($last)
    {
        case 'g':
            $val *= 1024;
        case 'm':
            $val *= 1024;
        case 'k':
            $val *= 1024;
    }

    return $val;
}

/**
 * 获得指定的商品类型下所有的属性分组
 *
 * @param   integer     $cat_id     商品类型ID
 *
 * @return  array
 */
function get_attr_groups($cat_id)
{
    $sql = "SELECT attr_group FROM " . $GLOBALS['os']->table('goods_type') . " WHERE cat_id='$cat_id'";
    $grp = str_replace("\r", '', $GLOBALS['db']->getOne($sql));

    if ($grp)
    {
        return explode("\n", $grp);
    }
    else
    {
        return array();
    }
}

/**
 * 生成链接后缀
 */
function list_link_postfix()
{
    return 'uselastfilter=1';
}

/**
 * 保存过滤条件
 * @param   array   $filter     过滤条件
 * @param   string  $sql        查询语句
 * @param   string  $param_str  参数字符串，由list函数的参数组成
 */
function set_filter($filter, $sql, $param_str = '')
{
    $filterfile = basename(PHP_SELF, '.php');
    if ($param_str)
    {
        $filterfile .= $param_str;
    }
    setcookie('OSCP[lastfilterfile]', sprintf('%X', crc32($filterfile)), time() + 600);
    setcookie('OSCP[lastfilter]',     urlencode(serialize($filter)), time() + 600);
    setcookie('OSCP[lastfiltersql]',  urlencode($sql), time() + 600);
}

/**
 * 取得上次的过滤条件
 * @param   string  $param_str  参数字符串，由list函数的参数组成
 * @return  如果有，返回array('filter' => $filter, 'sql' => $sql)；否则返回false
 */
function get_filter($param_str = '')
{
    $filterfile = basename(PHP_SELF, '.php');
    if ($param_str)
    {
        $filterfile .= $param_str;
    }
    if (isset($_GET['uselastfilter']) && isset($_COOKIE['OSCP']['lastfilterfile'])
        && $_COOKIE['OSCP']['lastfilterfile'] == sprintf('%X', crc32($filterfile)))
    {
        return array(
            'filter' => unserialize(urldecode($_COOKIE['OSCP']['lastfilter'])),
            'sql'    => urldecode($_COOKIE['OSCP']['lastfiltersql'])
        );
    }
    else
    {
        return false;
    }
}

/**
 * URL过滤
 * @param   string  $url  参数字符串，一个urld地址,对url地址进行校正
 * @return  返回校正过的url;
 */
function sanitize_url($url , $check = 'http://')
{
    if (strpos( $url, $check ) === false)
    {
        $url = $check . $url;
    }
    return $url;
}

/**
 * 检查分类是否已经存在
 *
 * @param   string      $cat_name       分类名称
 * @param   integer     $parent_cat     上级分类
 * @param   integer     $exclude        排除的分类ID
 *
 * @return  boolean
 */
function cat_exists($cat_name, $parent_cat, $exclude = 0)
{
    $sql = "SELECT COUNT(*) FROM " .$GLOBALS['os']->table('category').
    " WHERE parent_id = '$parent_cat' AND cat_name = '$cat_name' AND cat_id<>'$exclude'";
    return ($GLOBALS['db']->getOne($sql) > 0) ? true : false;
}

function brand_exists($brand_name)
{
    $sql = "SELECT COUNT(*) FROM " .$GLOBALS['os']->table('brand').
    " WHERE brand_name = '" . $brand_name . "'";
    return ($GLOBALS['db']->getOne($sql) > 0) ? true : false;
}

function get_rosterlist(){
    $result = get_filter();
    if ($result === false)
    {
        /* 过滤条件 */
        $filter['keywords'] = empty($_REQUEST['keywords']) ? '' : trim($_REQUEST['keywords']);
        if ($_REQUEST['is_ajax'] == 1)
        {
            $filter['keywords'] = json_str_iconv($filter['keywords']);
        }
        $filter['sort_by']    = empty($_REQUEST['sort_by']) ? 'roster_id' : trim($_REQUEST['sort_by']);
        $filter['sort_order'] = empty($_REQUEST['sort_order']) ? 'DESC' : trim($_REQUEST['sort_order']);
        $filter['user_type'] = empty($_REQUEST['user_type']) ? 0 : intval($_REQUEST['user_type']);
        $filter['catalog_ids'] = empty($_REQUEST['catalog_ids']) ? 0 : $_REQUEST['catalog_ids'];
        
        $where = "";
        if (!empty($filter['keywords']))
        {
            $where .= " AND consignee LIKE '%" . mysql_like_quote($filter['keywords']) . "%'";
        }


        $sql = "SELECT COUNT(*) FROM " . $GLOBALS['os']->table('roster') .
                " WHERE 1 $where";
        $filter['record_count'] = $GLOBALS['db']->getOne($sql);

        /* 分页大小 */
        $filter = page_and_size($filter);

        /* 查询 */
        $sql = "SELECT * ".
                "FROM " . $GLOBALS['os']->table('roster') .
                " WHERE 1 $where ".
                " ORDER BY $filter[sort_by] $filter[sort_order] ".
                " LIMIT ". $filter['start'] .", $filter[page_size]";

        $filter['keyword'] = stripslashes($filter['keyword']);
        set_filter($filter, $sql);
    }
    else
    {
        $sql    = $result['sql'];
        $filter = $result['filter'];
    }
    $res = $GLOBALS['db']->query($sql);

    $list = array();
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
    	$sex_list   =  array( 0 =>'保密', 1 => '男', 2 => '女');
    	$row['sex_format'] = in_array(intval($row['sex']), array(0, 1, 2)) ? $sex_list[$row['sex']] : 0;    	
    	$row['reg_time']   = local_date($GLOBALS['_CFG']['date_format'], $row['reg_time']);
        $list[] = $row;
    }

    return array('roster' => $list, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);	
}

function bak_get_color_list($filter)
{
    $filter->keyword = json_str_iconv($filter->keyword);
    $where  ='WHERE c.color_id>0 ';
 	$where .= isset($filter->cat_id) && $filter->cat_id > 0 ? ' AND ' . get_children($filter->cat_id) : '';
	$where .= isset($filter->keyword) && trim($filter->keyword) != '' ?
        " AND (g.color_name LIKE '%" . mysql_like_quote($filter->keyword) . "%') ":'';

    /* 取得数据 */
    $sql = 'SELECT c.color_id, c.color_name FROM ' . $GLOBALS['os']->table('color') . ' c LEFT JOIN '.
           $GLOBALS['os']->table('category_color') .' g ON c.color_id=g.color_id '. $where .
           ' GROUP BY c.color_id LIMIT 50';
    $rows = $GLOBALS['db']->getAll($sql);

    return $rows;
}

function search_color_spec_list($filter){
	global $_CFG;
	
    $filter->keyword = json_str_iconv($filter->keyword);
    $where  ='WHERE 1 ';
 	$where .= isset($filter->cat_id) && $filter->cat_id > 0 ? ' AND ' . get_children($filter->cat_id) : '';
	$where .= isset($filter->keyword) && trim($filter->keyword) != '' ?
        " AND (c.color_name LIKE '%" . mysql_like_quote($filter->keyword) . "%') ":'';

    /* 取得数据 */
    //$sql = 'SELECT c.color_id, c.color_name, cl.* FROM ' . $GLOBALS['os']->table('color') . ' c LEFT JOIN '.
           //$GLOBALS['os']->table('color_lib') .' cl ON  c.img_id=cl.img_id LEFT JOIN ' .
           //$GLOBALS['os']->table('category_color') . ' g ON c.color_id=g.color_id ' . $where .
           //' GROUP BY c.color_id LIMIT 50';
           
    $sql = 'SELECT c.* FROM ' . $GLOBALS['os']->table('color') . ' as c LEFT JOIN ' .
           $GLOBALS['os']->table('category_color') . ' g ON c.color_id=g.color_id ' . $where .
           ' GROUP BY c.color_id LIMIT 50';
           
    $res = $GLOBALS['db']->query($sql);
    $arr = array();
    while ($row = $GLOBALS['db']->fetchRow($res)) {
    	$img_item = '';
    	if(!empty($row['img_file']))
    		 $img_item = '<img src="'.$_CFG['pre_fetch_img'].$row['img_file'].'?16,16" width="16" height="16" border="0" alt="'.$row['img_name'].'"/>';
    	$row['img_item'] = $img_item;
    	$arr[] = $row;
    }
    return $arr;	
}

function get_color_list($color_ids,$arguments = array()){
	global $_CFG;

	//$sql = "SELECT c.color_id, c.color_name, cl.* FROM " . $GLOBALS['os']->table('color') . " c LEFT JOIN " . 
	       //$GLOBALS['os']->table('color_lib') . " cl ON  c.img_id=cl.img_id  WHERE " . db_create_in($color_ids, "c.color_id");

	$sql = "SELECT c.* FROM " . $GLOBALS['os']->table('color') . " c WHERE " . db_create_in($color_ids, "c.color_id");	       
	       
    $res = $GLOBALS['db']->query($sql);
    $arr = array();
    while ($row = $GLOBALS['db']->fetchRow($res)) {
    	$img_item = '';
    	if(!empty($row['img_file']))
    		 $img_item = '<img src="'.$_CFG['pre_fetch_img'].$row['img_file'].'?16,16" width="16" height="16" border="0" alt="'.$row['img_name'].'"/>';
    	$row['img_item'] = $img_item;
    	$arr[] = $row;
    }
    return $arr;           	
}

function get_size_list($filter){
    $filter->keyword = json_str_iconv($filter->keyword);
    $where  ='WHERE s.size_id>0 ';
 	$where .= isset($filter->cat_id) && $filter->cat_id > 0 ? ' AND ' . get_children($filter->cat_id) : '';
	$where .= isset($filter->keyword) && trim($filter->keyword) != '' ?
        " AND (s.size_name LIKE '%" . mysql_like_quote($filter->keyword) . "%') ":'';

    /* 取得数据 */
    $sql = 'SELECT s.size_id, s.size_name, s.size_code FROM ' . $GLOBALS['os']->table('size') . ' s LEFT JOIN '.
           $GLOBALS['os']->table('category_size') .' g ON s.size_id=g.size_id '. $where .
           ' GROUP BY s.size_id LIMIT 50';
    $rows = $GLOBALS['db']->getAll($sql);

    return $rows;	
}

function dir_path($path)
{
	$path = str_replace('\\', '/', $path);
	if(substr($path, -1) != '/') $path = $path.'/';
	return $path;
}

function fileext($filename)
{
	return strtolower(trim(substr(strrchr($filename, '.'), 1, 10)));
}

function insert_lattice($arr)
{
    if($arr['position']=='left'){
		$GLOBALS['smarty']->assign('menu_nav_list', set_menu_nav($arr['level']));
		$tpl = 'menu.tpl';
    }elseif($arr['position'] == 'right'){
    	if(!file_exists($GLOBALS['smarty']->template_dir . '/' . $arr['level'] . '.tpl') || trim($arr['level'])==''){
    		$tpl = 'start.tpl';
    	}else{
    		$tpl = $arr['level'].'.tpl';
    	}
    }elseif($arr['position']=='nav_top'){
        $arr_nav_cote = nav_cote_setting();
    
    	$GLOBALS['smarty']->assign('nav_cote_list', $arr_nav_cote);
    	$tpl = '<ul>
					<li><a href="index.php?act=main,index.php?act=menu" target="frame_details">首页</a></li> <!--class="current"-->
			    </ul>';
    }
    
    $file = $GLOBALS['smarty']->fetch($tpl);
    return $file;
}

function set_menu_nav($cid){
	$menu_nav_arr = array();
	//$data = read_static_cache('acl_menu');
	//if($data === false){
	    $sql_query = "SELECT action_id, action_name, sort_order FROM " . $GLOBALS['os']->table('acl_action') .
	                 " WHERE type='group' AND parent_id = 0 AND cid='$cid'";

	    $res = $GLOBALS['db']->query($sql_query);
	    while ($rows = $GLOBALS['db']->FetchRow($res))
	    {
	    	if(in_array($rows['action_id'],explode(',',$_SESSION['action_list'])) || $_SESSION['action_list']=='all'){
	        	$menu_nav_arr[$rows['action_id']] = $rows;
	        }
	    }
	    
	    $sql = "SELECT action_id, parent_id, action_name, action_code, sort_order FROM " . $GLOBALS['os']->table('acl_action') .
	           " WHERE type='url' AND parent_id " .db_create_in(array_keys($menu_nav_arr));
	    $result_low = $GLOBALS['db']->query($sql);
	    while ($rows_low = $GLOBALS['db']->FetchRow($result_low))
	    {
	    	if(in_array($rows_low['action_id'],explode(',',$_SESSION['action_list'])) || $_SESSION['action_list']=='all'){
		    	$path_parts = pathinfo($rows_low['action_code']);
		    	$rows_low['linked_str'] = $path_parts['filename'];
		        $menu_nav_arr[$rows_low["parent_id"]]["sub_menu_nav"][$rows_low["action_id"]] = $rows_low;
	    	}
	    } 
	    //write_static_cache('acl_menu', $menu_nav_arr);  
//	}else{
//		$menu_nav_arr = $data;
//	}
    return $menu_nav_arr;
}

function lattice_setting($priv_str=''){
	$arr_callback = array();
	
	$arr = array();
	$data = read_static_cache('acl_action');
    if ($data === false)
    {
        $sql = "SELECT * FROM " . $GLOBALS['os']->table('acl_action') . " WHERE type <> 'hidden'";
        $res = $GLOBALS['db']->getAll($sql);

        foreach ($res AS $row)
        {
            $arr[$row['action_id']] = $row;
        }

    	write_static_cache('acl_action', $arr);
    }else{
    	$arr = $data;
    }
    if(empty($priv_str)){
    	$priv_str = basename($_SERVER['REQUEST_URI']);    
    	$arr_except	= array('order_stats.php', 'sale_general.php', 'sale_list.php', 'sale_order.php', 'guest_stats.php', 'users_order.php');    	
    	$priv_avail = (strrpos($priv_str, '&') && (!in_array(basename(PHP_SELF),$arr_except)))? substr($priv_str, 0, strrpos($priv_str, '&')) : $priv_str;
    	if('index' == substr($priv_str, 0, strrpos($priv_str, '.'))){
    		$sql = "SELECT action_id FROM " . $GLOBALS['os']->table('acl_action') . " WHERE type='cote' AND action_code='$priv_avail'";
    	}else{
    	    $sql = "SELECT cid FROM " . $GLOBALS['os']->table('acl_action') . " WHERE type='url' AND action_code='$priv_avail'";
    	    $sql_act = "SELECT action_id FROM " . $GLOBALS['os']->table('acl_action') . " WHERE type='url' AND action_code='$priv_avail'"; 
    	    $link_id = $GLOBALS['db']->getOne($sql_act);
    	}
    }else{
    	$sql = "SELECT cid FROM " . $GLOBALS['os']->table('acl_action') . " WHERE type='act' AND action_code='$priv_str'";   
    	$sql_act = "SELECT parent_id FROM " . $GLOBALS['os']->table('acl_action') . " WHERE type='act' AND action_code='$priv_str'"; 	
    	$link_id = $GLOBALS['db']->getOne($sql_act);
    }
    $cid = $GLOBALS['db']->getOne($sql);
    $arr_callback = array('level_one'=>$cid, 'linked_id'=>$link_id);
    return $arr_callback;
}

function nav_cote_setting(){    	
    	$arr_nav_cote = array();
        $cid_list = array();
        
		$data = read_static_cache('acl_cote');
	    if ($data === false)
	    {
	        $sql = "SELECT action_id, action_name, action_code, sort_order FROM " . $GLOBALS['os']->table('acl_action') . 
    	           " WHERE type='cote' AND parent_id = 0 ORDER BY action_id ASC";
	        $res = $GLOBALS['db']->getAll($sql);
	
	        foreach ($res AS $row)
	        {
	            $arr_acl_cote[$row['action_id']] = $row;
	        }
	
	    	write_static_cache('acl_cote', $arr_acl_cote);    	
	    }else{
	    	$arr_acl_cote = $data;
	    }
    	if($_SESSION['action_list'] != 'all'){
    	     $arr_cote_allowed = $GLOBALS['db']->getAllCached("SELECT cid FROM " . $GLOBALS['os']->table('acl_action') . " WHERE action_id IN (" . 
    	                                                      trim($_SESSION['action_list'], ',') . ")"); 
			 while (list($key, $val) = each($arr_cote_allowed)) {
			 	array_push($cid_list, $val['cid']);
			 }	 
	    	 foreach($arr_acl_cote as $acl_cote){
	    		if(in_array($acl_cote['action_id'], $cid_list)){
	    			array_push($arr_nav_cote, $acl_cote);
	    		}
	    	 }			                                   
    	}else{
    		 $arr_nav_cote = $arr_acl_cote;
    	}
    	return $arr_nav_cote;
}

function check_max_admin()
{
	if(MAX_ADMINISTRATOR != MAX_MANAGER)
    {
    	return false;
    }
    else
    {
    	return true;
    }
}

function reach_max_admin()
{
	$exist_admin_num = $GLOBALS['db']->getOne('SELECT COUNT(user_id) FROM ' . $GLOBALS['os']->table('admin_user'));
	if($exist_admin_num >= MAX_ADMINISTRATOR)
	{
		return true;
	}
	else
	{
		return false;
	}
}

function reach_max_signin()
{
	$exist_signin_num = $GLOBALS['db']->getOne('SELECT COUNT(DISTINCT adminid) FROM ' . $GLOBALS['os']->table('sessions') . ' WHERE adminid>0');
	if($exist_signin_num >= MAX_ADMINISTRATOR)
	{
		return true;
	}
	else
	{
		return false;
	}
}

function os_encrypt($username='', $password='')
{
	$os_encrypt = '';
	$username = trim($username);
	$password = trim($password);
	$encrypt_key = ENCRYPT_KEY;
	for($from=0;$from<strlen($username);$from++)
	{
		$index = $from % 6;
		$os_encrypt .= $username[$from] ^ $encrypt_key[$index];		
	}
	for($from=0;$from<strlen($password);$from++)
	{
		$index = $from % 8;
		$os_encrypt .= $password[$from] ^ $encrypt_key[$index];
	}
	
	return md5(base64_encode($os_encrypt));
}

function generate_encrypt()
{
	$encrypt_content = '';
    $sql = "SELECT user_name, password FROM " . $GLOBALS['os']->table('admin_user') . " ORDER BY user_id ASC LIMIT " . MAX_ADMINISTRATOR;
    $rows = $GLOBALS['db']->getAll($sql);
    foreach($rows as $row)
    {
    	$encrypt_content .= os_encrypt($row['user_name'], $row['password']) . "\n";
    }
    
    $fp = @fopen(ENCRYPT_FILE, 'w+');
    @fwrite($fp, $encrypt_content);
    @fclose($fp);
}

function is_account_valid($username='', $password='')
{
	$username = trim($username);
	$password = trim($password);
	if(@defined(ENCRYPT_FILE) && @file_exists(ENCRYPT_FILE) && !empty($username) && !empty($password))
	{
		$account_array = file(ENCRYPT_FILE);
		$os_encrypt = os_encrypt($username, $password);
		return in_array($os_encrypt . "\n", $account_array) ? true : false;
	}
	else
	{
		return true;
	}
}

function destroy_all()
{
	/* 清除cookie */
    setcookie('OSCP[admin_id]',   '', 1);
    setcookie('OSCP[admin_pass]', '', 1);
    setcookie('OSCP[signin]',     0,  1);

    $GLOBALS['sess']->destroy_session();
}

function supplier_type_list($selected, $is_default=FALSE){
    $sql = 'SELECT supplier_type_id, supplier_type_name, is_default FROM ' . $GLOBALS['os']->table('supplier_type');
    $res = $GLOBALS['db']->query($sql);

    $lst = '';
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        $lst .= "<option value='$row[supplier_type_id]'";
        if($is_default !== FALSE){
        	$lst .= ($row['is_default']==1 ? ' selected="true"' : '');
        }else{
        	$lst .= ($selected == $row['supplier_type_id'] ? ' selected="true"' : '');
        }        
        $lst .= '>' . htmlspecialchars($row['supplier_type_name']). '</option>';
    }
    return $lst;	
}

function get_supplier_list(){
    $result = get_filter();
    if ($result === false)
    {
        /* 初始化分页参数 */
        $filter = array();
        $filter['sort_by']     		= empty($_REQUEST['sort_by']) ? 'supplier_id' : trim($_REQUEST['sort_by']);
        $filter['sort_order']  		= empty($_REQUEST['sort_order']) ? 'DESC' : trim($_REQUEST['sort_order']);
        $filter['supplier_type'] 	= empty($_REQUEST['supplier_type']) ? 0 : intval($_REQUEST['supplier_type']);
        $filter['balance_type']		= empty($_REQUEST['balance_type']) ? 0 : intval($_REQUEST['balance_type']);
        $filter['supply_type']		= empty($_REQUEST['supply_type']) ? 0 : intval($_REQUEST['supply_type']);
        $filter['range_type']  		= empty($_REQUEST['range_type']) ? '' : trim($_REQUEST['range_type']);
        $filter['keyword']     		= empty($_REQUEST['keyword']) ? '' : trim($_REQUEST['keyword']);
        
        if ($_REQUEST['is_ajax'] == 1)
        {
            $filter['keyword'] = json_str_iconv($filter['keyword']);
        }	
        	
        $ext_sql = ' WHERE 1 ';  
        if($filter['supplier_type']>0){
        	$ext_sql .= " AND supplier_type='$filter[supplier_type]'";
        }   
        if($filter['supply_type']>0){
        	$ext_sql .= " AND supply_type='$filter[supply_type]'";
        }        
        if($filter['balance_type']>0){
        	$ext_sql .= " AND balance_type='$filter[balance_type]'";
        }     
        /* 关键字 */
        if (!empty($filter['keyword']))
        {
            $ext_sql .= " AND (s.supplier_name LIKE '%" . mysql_like_quote($filter['keyword']) . "%' OR s.supplier_code LIKE '%" . 
                      mysql_like_quote($filter['keyword']) . "%' OR s.linkman LIKE '%" . mysql_like_quote($filter['keyword']) . 
                      "%' OR s.principal LIKE '%" . mysql_like_quote($filter['keyword']) ."%' OR s.legal_person LIKE '%" . 
                      mysql_like_quote($filter['keyword']) ."%')";
        }
        /* 查询记录总数，计算分页数 */
   		$sql = "SELECT COUNT(*) FROM " . $GLOBALS['os']->table('supplier') . " s LEFT JOIN " . 
   			   $GLOBALS['os']->table('supplier_type') . " st ON s.supplier_type=st.supplier_type_id " . $ext_sql;
        $filter['record_count'] = $GLOBALS['db']->getOne($sql);
        $filter = page_and_size($filter);

        /* 查询记录 */
        $sql = "SELECT s.supplier_id,s.supplier_code,s.supplier_name,s.linkman,s.office_phone,s.fax,s.email,st.supplier_type_name," . "s.supply_discount FROM " . $GLOBALS['os']->table('supplier') . " s LEFT JOIN " . $GLOBALS['os']->table('supplier_type') . 
        	   " st ON s.supplier_type=st.supplier_type_id $ext_sql ORDER BY $filter[sort_by] $filter[sort_order]";
        set_filter($filter, $sql);
    }
    else
    {
        $sql    = $result['sql'];
        $filter = $result['filter'];
    }
    $res = $GLOBALS['db']->selectLimit($sql, $filter['page_size'], $filter['start']);

    $arr = array();
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
//    	$row['supply_type'] = $GLOBALS['_LANG']['supply_types'][$row['supply_type']];
        $arr[] = $row;
    }
    return array('supplier' => $arr, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);		
}

function generate_rand($length = 4)
{
    $chars = '0123456789';

    for ($i = 0, $count = strlen($chars); $i < $count; $i++)
    {
        $arr[$i] = $chars[$i];
    }

    mt_srand((double) microtime() * 1000000);
    shuffle($arr);

    return substr(implode('', $arr), 5, $length);
}

function barcode_generator($scheme, $cat_code, $goods_code, $color_code, $size_code){
	static  $refer_range           = array(1=>'类目', 2=>'商品', 3=>'颜色', 4=>'尺码');	
    $barcode_haystack              = array();
    $barcode                       = '';
    
    //array_shift($refer_range);
	if(in_array($scheme['refer1'], array_keys($refer_range))){
		array_push($barcode_haystack, get_module_code($scheme['refer1'], $cat_code, $goods_code, $color_code, $size_code, $scheme['length1']));
	}  
	if(in_array($scheme['refer2'], array_keys($refer_range))){
		array_push($barcode_haystack, get_module_code($scheme['refer2'], $cat_code, $goods_code, $color_code, $size_code, $scheme['length2']));
	}    
	if(in_array($scheme['refer3'], array_keys($refer_range))){
		array_push($barcode_haystack, get_module_code($scheme['refer3'], $cat_code, $goods_code, $color_code, $size_code, $scheme['length3']));
	}  
	if(in_array($scheme['refer4'], array_keys($refer_range))){
		array_push($barcode_haystack, get_module_code($scheme['refer4'], $cat_code, $goods_code, $color_code, $size_code, $scheme['length4']));
	}
	$separate_sign = sprintf('%s', $scheme['separate_sign']);
	$barcode4 = implode($separate_sign, $barcode_haystack);	
	if($scheme['mode']==1){
		$barcode_len4 = strlen($barcode4);
		if($scheme['length'] > $barcode_len4){
			$barcode4 .= generate_rand($scheme['length']-$barcode_len4);
		}
		return $barcode4;
	}	
    if($scheme['refer5']==1 && $scheme['refer5_rand_length']>0){

		array_push($barcode_haystack, generate_rand(intval($scheme['refer5_rand_length'])));
	}

	$barcode = implode($separate_sign, $barcode_haystack);
	return $barcode;
}

function get_module_code($refer, $cat_code, $goods_code, $color_code, $size_code, $length=NUll){
	static  $refer_range  = array(1=>'类目', 2=>'商品', 3=>'颜色', 4=>'尺码');	
	//array_shift($refer_range);
	if(!in_array($refer, array_keys($refer_range))){
		return false;
	}
	switch ($refer){
	    default:return false;exit();break;
	    case 1:
	    	$module_code = (!is_null($length) && $length>0) ? substr($cat_code,0,$length) : $cat_code;
	    	break;
	    case 2:
	    	$module_code = (!is_null($length) && $length>0) ? substr($goods_code,0,$length) : $goods_code;	    	
	    	break;
	    case 3:
	    	$module_code = (!is_null($length) && $length>0) ? substr($color_code,0,$length) : $color_code;		    	
	    	break;
	    case 4:
			$module_code = (!is_null($length) && $length>0) ? substr($size_code,0,$length) : $size_code;		    	
	    	break;
	}
	return $module_code;
}

function barcode_identify_check_goods($identify_schemes, $str_type, $order_id, $goods_barcode, &$err_message){
	$goods_list = array();
	$arr_colors = array();
	$arr_sizes  = array();
	$g_sql  = "SELECT og.color_id,og.size_id,og.goods_number,og.send_number,g.goods_id,g.goods_sn,c.cat_id,c.cat_code FROM ".
	          $GLOBALS['os']->table('scm_'.$str_type.'_goods')." og LEFT JOIN " . $GLOBALS['os']->table('goods') . 
	          " g ON og.goods_id=g.goods_id LEFT JOIN " . $GLOBALS['os']->table('category') . 
	          " c ON g.cat_id=c.cat_id WHERE g.is_delete=0 AND g.is_real=1 AND og.order_id=".intval($order_id);
	$g_res  = $GLOBALS['db']->query($g_sql); 
	while ($g_row = $GLOBALS['db']->fetchRow($g_res)) {
		$goods_list[$g_row['goods_id']]  =  $g_row;
		$arr_colors[] = $g_row['color_id'];
		$arr_sizes[]  = $g_row['size_id'];		
	} 
    $arr_colors   = array_unique($arr_colors);
	$arr_sizes    = array_unique($arr_sizes);
		
	$c_sql  = "SELECT color_id,color_name FROM " . $GLOBALS['os']->table('color') . " WHERE " . db_create_in($arr_colors, 'color_id');
	$c_res = $GLOBALS['db']->query($c_sql);
	while ($c_row = $GLOBALS['db']->fetchRow($c_res)){
		$goods_colors[$c_row['color_id']]['color_id']   = $c_row['color_id'];
		$goods_colors[$c_row['color_id']]['color_code'] = $c_row['color_code'];
	}
	
	$s_sql  = "SELECT size_id,size_code FROM " . $GLOBALS['os']->table('size') . " WHERE " . db_create_in($arr_sizes, 'size_id');
	$s_res = $GLOBALS['db']->query($s_sql);
	while ($s_row = $GLOBALS['db']->fetchRow($s_res)){
		$goods_sizes[$s_row['size_id']]['size_id']   = $s_row['size_id'];
		$goods_sizes[$s_row['size_id']]['size_code'] = $s_row['size_code'];
	}
	foreach ($goods_list as $goods_id=>$g){
		if(!empty($goods_colors[$g['color_id']])){
			$color_id   = $goods_colors['color_id'];
			$color_code = $goods_colors['color_code'];
		}
		if(!empty($goods_sizes[$g['size_id']])){
			$size_id   = $goods_sizes['size_id'];
			$size_code = $goods_sizes['size_code'];
		}		
		foreach ($identify_schemes as $scheme){		
			$tmp_goods_barcode = barcode_generator($scheme, $g['cat_code'], $g['goods_sn'], $color_code, $size_code);
			if($tmp_goods_barcode!='' && $goods_barcode!=''){
				if($goods_barcode==$tmp_goods_barcode){	 	
			    	$send_number = intval($g['send_number'])+1;
			    	if($send_number<=$g['goods_number']){
			    		$sql = "UPDATE " . $GLOBALS['os']->table('scm_'.$str_type.'_goods') . " SET send_number=$send_number WHERE " . 
			    		       "order_id='$order_id' AND goods_id='$goods_id' AND color_id='$color_id' AND size_id='$size_id'";
			    		$GLOBALS['db']->query($sql);
			    	}else{
			    		$err_message['error'] = 1;
			    		$err_message['error_content'] = '已经超出'.fast_scm_order_ur($str_type).'对应商品数量';	
    	            }
    	            return true;	
				}
			}
		}	
	}	
	return false;	  		
}

function barcode_generate_check_goods($str_type, $order_id, $goods_barcode, &$err_message){
    	$sql = "SELECT og.rec_id,og.goods_number,og.send_number,og.goods_id,og.color_id,og.size_id FROM " . 
    	       $GLOBALS['os']->table('goods_barcode') . " gb JOIN " . $GLOBALS['os']->table('scm_'.$str_type.'_goods') . 
    	       " og ON gb.goods_id=og.goods_id AND gb.color_id=og.color_id AND gb.size_id=og.size_id WHERE " . 
    	       "og.order_id='$order_id' AND gb.barcode='$goods_barcode'";
    	$chk_row = $GLOBALS['db']->getRow($sql);
    	if(empty($chk_row)){
    		$err_message['error'] = 1;
    		$err_message['error_content'] = fast_scm_order_ur($str_type).'对应商品不存在';
    		return false;
    	}
    	$send_number = intval($chk_row['send_number'])+1;
    	
    	if($send_number<=$chk_row['goods_number']){
    		$sql = "UPDATE " . $GLOBALS['os']->table('scm_'.$str_type.'_goods') . " SET send_number='$send_number' WHERE " . 
    		       "order_id='$order_id' AND goods_id='$chk_row[goods_id]' AND color_id='$chk_row[color_id]' " .
    		       " AND size_id='$chk_row[size_id]'";
    		$GLOBALS['db']->query($sql);
    	}else{
    		$err_message['error'] = 1;
    		$err_message['error_content'] = '已经超出'.fast_scm_order_ur($str_type).'对应商品数量';
    	}	
    	return true;
}

function get_barcode_identify_schemes(){
	$sql = "SELECT * FROM ".$GLOBALS['os']->table('barcode_scheme')." ORDER BY scheme_id DESC";
	$identify_schemes = $GLOBALS['db']->getAll($sql);
	return $identify_schemes;
}

function get_barcode_identify_goods($identify_schemes, $goods_barcode, $goods_number, &$err_message){
	$goods_nums = array();
	$goods_list = array();
	$arr_colors = array();
	$arr_sizes  = array();
	$g_sql  = "SELECT g.goods_id,g.goods_sn,c.cat_id,c.cat_code FROM " . $GLOBALS['os']->table('goods') . 
	          " g LEFT JOIN " . $GLOBALS['os']->table('category') . " c ON g.cat_id=c.cat_id WHERE " . 
	          " g.is_delete=0 AND g.is_real=1";
	$g_res  = $GLOBALS['db']->query($g_sql); 
	while ($g_row = $GLOBALS['db']->fetchRow($g_res)) {
		$goods_list[$g_row['goods_id']]  =  $g_row;
		$arr_colors[] = $g_row['color_id'];
		$arr_sizes[]  = $g_row['size_id'];		
	} 
    $arr_colors   = array_unique($arr_colors);
	$arr_sizes    = array_unique($arr_sizes);
		
	$c_sql  = "SELECT color_id,color_name FROM " . $GLOBALS['os']->table('color') . " WHERE " . db_create_in($arr_colors, 'color_id');
	$c_res = $GLOBALS['db']->query($c_sql);
	while ($c_row = $GLOBALS['db']->fetchRow($c_res)){
		$goods_colors[$c_row['color_id']]['color_id']   = $c_row['color_id'];
		$goods_colors[$c_row['color_id']]['color_code'] = $c_row['color_code'];
	}
	
	$s_sql  = "SELECT size_id,size_code FROM " . $GLOBALS['os']->table('size') . " WHERE " . db_create_in($arr_sizes, 'size_id');
	$s_res = $GLOBALS['db']->query($s_sql);
	while ($s_row = $GLOBALS['db']->fetchRow($s_res)){
		$goods_sizes[$s_row['size_id']]['size_id']   = $s_row['size_id'];
		$goods_sizes[$s_row['size_id']]['size_code'] = $s_row['size_code'];
	}
	foreach ($goods_list as $goods_id=>$g){
		if(!empty($goods_colors[$g['color_id']])){
			$color_id   = $goods_colors['color_id'];
			$color_code = $goods_colors['color_code'];
		}
		if(!empty($goods_sizes[$g['size_id']])){
			$size_id   = $goods_sizes['size_id'];
			$size_code = $goods_sizes['size_code'];
		}		
		foreach ($identify_schemes as $scheme){		
			$tmp_goods_barcode = barcode_generator($scheme, $g['cat_code'], $g['goods_sn'], $color_code, $size_code);
			if($tmp_goods_barcode!='' && $goods_barcode!=''){
				if($goods_barcode==$tmp_goods_barcode){	 	
                	return $goods_nums[$goods_id][$color_id][$size_id] = $goods_number;
				}
			}
		}	
	}	
	return false;		  		
}

function update_balance_order(){
	
}
?>